package demo.huodongbaoming.controller;

import demo.huodongbaoming.dto.ResponseResult;
import demo.huodongbaoming.entity.ActivityCategory;
import demo.huodongbaoming.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityNotFoundException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/categories")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public ResponseResult<ActivityCategory> createCategory(@RequestBody Map<String, String> request) {
        try {
            String name = request.get("name");
            String description = request.get("description");
            ActivityCategory category = categoryService.createCategory(name, description);
            return ResponseResult.success("类别创建成功", category);
        } catch (Exception e) {
            return ResponseResult.fail(400, e.getMessage());
        }
    }

    @GetMapping("/{id}")
    public ResponseResult<ActivityCategory> getCategoryById(@PathVariable Long id) {
        try {
            ActivityCategory category = categoryService.getCategoryById(id);
            return ResponseResult.success(category);
        } catch (EntityNotFoundException e) {
            return ResponseResult.fail(404, e.getMessage());
        }
    }

    @GetMapping
    public ResponseResult<List<ActivityCategory>> getAllCategories() {
        List<ActivityCategory> categories = categoryService.getAllCategories();
        return ResponseResult.success(categories);
    }

    @PutMapping("/{id}")
    public ResponseResult<ActivityCategory> updateCategory(@PathVariable Long id, @RequestBody Map<String, String> request) {
        try {
            String name = request.get("name");
            String description = request.get("description");
            ActivityCategory category = categoryService.updateCategory(id, name, description);
            return ResponseResult.success("类别更新成功", category);
        } catch (EntityNotFoundException e) {
            return ResponseResult.fail(404, e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public ResponseResult<Void> deleteCategory(@PathVariable Long id) {
        try {
            categoryService.deleteCategory(id);
            return ResponseResult.success("类别删除成功", null);
        } catch (EntityNotFoundException e) {
            return ResponseResult.fail(404, e.getMessage());
        }
    }
} 